package com.yu.crm.controller;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.crm.domain.pojo.CrmEigenvalue;
import com.yu.crm.service.impl.CrmEigenvalueService;
import com.yu.crm.utils.DateUtil;
import com.yu.crm.utils.EigenValue;
import com.yu.crm.utils.FileUtil;
import com.yu.crm.utils.TicketUtil;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.valid.ValidatorHelpers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 人脸特征值对比表 前端控制器
 * </p>
 *
 * @author ct
 * @since 2019-12-23
 */
@Api(tags = "人脸特征值对比表管理")
@RestController
@RequestMapping("/crm-eigenvalue")
public class CrmEigenvalueController {
    @Autowired
    CrmEigenvalueService crmEigenvalueService;

    @ApiOperation(value = "新增人脸特征值")
    @PostMapping(value = "/add")
    public void add(@RequestBody CrmEigenvalue crmEigenvalue) {
        crmEigenvalueService.add(crmEigenvalue);
    }

    @ApiOperation(value = "通过id修改人脸特征值")
    @PostMapping(value = "/update")
    public void update(@RequestBody CrmEigenvalue crmEigenvalue) {
        crmEigenvalueService.update(crmEigenvalue);
    }

    @ApiOperation(value = "通过编号查询人脸特征值")
    @GetMapping(value = "/get-by-id")
    public CrmEigenvalue infoById(@RequestParam Long id) {
        ValidatorHelpers.notEmpty(id,"主键不能为空");
        return crmEigenvalueService.infoById(id);
    }

    @ApiOperation(value = "查询访客人脸特征值集合")
    @GetMapping(value = "/list-by-type")
    public List<CrmEigenvalue> listCrmEigenvalueByType(@RequestParam Integer type) {
        return crmEigenvalueService.listCrmEigenvalueByType(type);
    }

    /**
     * 通过用户id修改
     * @param crmEigenvalue
     */
    @ApiOperation(value = "通过用户id修改人脸特征值")
    @PostMapping(value = "/update-by-userid")
    public void updateByUserId(@RequestBody CrmEigenvalue crmEigenvalue) {
        ValidatorHelpers.notEmpty(crmEigenvalue.getUserId(),"用户编号不能为空");
        crmEigenvalueService.updateByUserId(crmEigenvalue);
    }

    @ApiOperation(value = "通过编号删除人脸特征值")
    @PostMapping(value = "/delete-by-id")
    public void deleteById(@RequestParam Long id) {
        ValidatorHelpers.notEmpty(id,"主键不能为空");
        crmEigenvalueService.deleteById(id);
    }

//    @ApiOperation(value = "获取开门条件")
//    @PostMapping(value = "/open-by-ticket")
//    public String openConditionByTicket(String identityId){
//        String resultMsg  = TicketUtil.request();
//        if(null != resultMsg && "" != resultMsg){
//            List<String> IDCards = new ArrayList<>();
//            List<LocalDateTime> busStartTimes = new ArrayList<>();
//            if(IDCards.contains(identityId)){
//
//
//
//                return "success";
//            }
//        }
//        return "fail";
//    }

    @ApiOperation(value = "人脸开门")
    @PostMapping(value = "/open-by-eigenvalue")
    public void openDeviceByEigenvalue(@RequestBody HashMap<String,Object> map){
        ValidatorHelpers.notEmpty(map.get("eigenvalues"),"用户特征值不能为空");
        ValidatorHelpers.notEmpty(map.get("cameraNumber"),"摄像头标识不能为空");
        ValidatorHelpers.notEmpty(map.get("cameraImageBase64"),"图片不能为空");
        crmEigenvalueService.openDeviceByEigenvalue(map);
    }

    /**
     * 通过图片url生成特征值
     * @param imageUrl   格式 http://fkgzh.whyxzz.net/person_img/201908/6b9b2e4ef65740539411c7709ba065bb.jpg
     * @return
     */
    @ApiOperation(value = "通过图片url生成特征值")
    @GetMapping(value = "/send-extractFeature-imgurl")
    public byte[]  extractFeatureImageUrl(@Param("imageUrl") String imageUrl) {
        byte[] bytes = EigenValue.extractFeatureImageUrl(imageUrl);
        System.out.println("========"+bytes.length);
        return bytes;
    }

    /**
     * 通过图片流生成特征值
     * @param file
     * @return
     */
    @ApiOperation(value = "通过图片流生成特征值")
    @PostMapping(value = "/send-extractFeature-file")
    public byte[]  sendExtractFeatureFile(MultipartFile file) {
        byte[] bytes = EigenValue.sendExtractFeatureFile(file);
        System.out.println("========"+bytes.length);
        return bytes;
    }

    @ApiOperation(value = "通过userId查询记录")
    @GetMapping(value = "/list-by-userId")
    public List<CrmEigenvalue> listCrmEigenvalueByUserId(@RequestParam String userId) {
        return crmEigenvalueService.listCrmEigenvalueByUserId(userId);
    }


    @GetMapping(value = "/aaa")
    public void aaa() {
        crmEigenvalueService.aaa();
    }

    @ApiOperation(value = "特征值记录")
    @PostMapping(value = "/save-eigenvalue")
    public void saveEigenvalue(@RequestBody HashMap<String,Object> map){
        ValidatorHelpers.notEmpty(map.get("eigenvalues"),"用户特征值不能为空");
        ValidatorHelpers.notEmpty(map.get("cameraNumber"),"摄像头标识不能为空");
        crmEigenvalueService.saveEigenvalue(map);
    }

    @ApiOperation(value = "通过类型type 查询记录")
    @GetMapping(value = "/page-by-type")
    public IPage<CrmEigenvalue> listCrmEigenvalueByType(Page<CrmEigenvalue> page, CrmEigenvalue queryInfo) {

        ValidatorHelpers.notEmpty(queryInfo.getType(), "查询类型值不能为空");
        return crmEigenvalueService.pageByQueryInfo(page, queryInfo);
    }

    @ApiOperation(value = "上传图片并查询")
    @PostMapping(value = "/list-by-pic")
    public Map<String, Object> listCrmEigenvalueByType(Page<CrmEigenvalue> page, MultipartFile file) {
        //图片上传
        String picUrl = FileUtil.uploadPictures(file);

        if (picUrl == null) {
            throw new GeneralException("上传图片失败");
        }

        CrmEigenvalue queryInfo = new CrmEigenvalue();
        queryInfo.setCertificateBase(picUrl);
        Map<String, Object> map = new HashMap<>();

        List<CrmEigenvalue> crmEigenvalues =crmEigenvalueService.listByQueryInfo(queryInfo);

        //查询结果
        map.put("list",crmEigenvalues);

        //查询结果统计
        map.putAll(count(crmEigenvalues));

        //图片地址
        map.put("picture", picUrl);
        return map;
    }


    @ApiOperation(value = "根据特征值和时间进行查询")
    @GetMapping(value = "/page-by-date")
    public List<CrmEigenvalue> pageBydate(CrmEigenvalue queryInfo) {
        ValidatorHelpers.notEmpty(queryInfo.getCertificateBase(), "查询图片不能为空");
        return crmEigenvalueService.listByQueryInfo(queryInfo);
    }

    @ApiOperation("总抓拍人数")
    @GetMapping(value = "/countALL")
    public Integer coutAll(){
        return crmEigenvalueService.count();
    }



    @ApiOperation("统计本周本月本日的人数分布")
    @GetMapping(value = "/countMap")
    public Map<String,List<Integer>> coutMap(){
        CrmEigenvalue queryInfo =new CrmEigenvalue();
        Map<String ,List<Integer>> map = new HashMap<>();
        //本周第一天
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK,1);
        //本月第一天
        Calendar cal2=Calendar.getInstance();
        cal2.set(Calendar.DAY_OF_MONTH,1);

        //定义12个值分别存放 本日  本周 本月 四类人的值

        List<Integer> day =new ArrayList<>();
        List<Integer> week =new ArrayList<>();
        List<Integer> month =new ArrayList<>();
        //初始化
        for (int i = 0; i <4 ; i++) {
            day.add(0);
            week.add(0);
            month.add(0);
        }
        SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd");

        queryInfo.setStartDate(dateformat.format(cal2.getTime()));
        List<CrmEigenvalue> list =crmEigenvalueService.listByQueryInfo(queryInfo);

        Duration duration = Duration.between(DateUtil.date2LocalDateTime(cal.getTime()), LocalDateTime.now());
        //本周第一天和本日相隔天数
        long week1 = duration.toDays();




        Duration duration2 = Duration.between(DateUtil.date2LocalDateTime(cal2.getTime()), LocalDateTime.now());
        //本月第一天和本日相隔天数
        long month2 = duration2.toDays();


        for (CrmEigenvalue value:list) {
            value.getGmtCreate().toLocalDate().toEpochDay();
            long l =LocalDate.now().toEpochDay()-value.getGmtCreate().toLocalDate().toEpochDay();
            Integer type = value.getType()-1;
            if (l==0){
                day.set(type,day.get(type)+1);
            }

            if (l<=week1){
                week.set(type,week.get(type)+1);
            }

            if (l<month2){
                month.set(type,month.get(type)+1);
            }


        }
        map.put("day",day);
        map.put("week",week);
        map.put("month",month);
        return map;
    }

    private Map<String,Integer> count(List<CrmEigenvalue> crmEigenvalues ){

        Map<String,Integer> map = new HashMap<>();
        //本月统计
        map.put("month",crmEigenvalues.size());



        //本周第一天
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK,1);

        Duration duration = Duration.between(DateUtil.date2LocalDateTime(cal.getTime()), LocalDateTime.now());
        //本周第一天和本日相隔天数
        long weekl = duration.toDays();


        int week=0;
        int day =0;
        for (CrmEigenvalue value:crmEigenvalues){
            Duration duration2 = Duration.between(value.getGmtCreate(), LocalDateTime.now());
            long l = duration2.toDays();
            //统计本日记录
            if (l<1){
                day++;
            }

            if (l <=weekl){
                week++;
            }
        }
        map.put("week",week);
        map.put("day",day);
        return map;

    }


}

